package com.miniapi.api.services;

import org.json.JSONObject;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.miniapi.api.common.Filemanege;
import com.miniapi.api.common.StringUtils;
import com.miniapi.api.entities.QrCodeForPromotion;
import com.miniapi.api.entities.User;
import com.miniapi.api.repositories.QrCodeRepository;
import com.miniapi.api.repositories.UserRepository;

import ybl.wechat.WeChatService;

@Component
public class WeChatClickService {
    @Autowired
    private QrCodeRepository qrCodeRepository;

    @Autowired
    private UserRepository userRepository;

    /**
     * 处理点击获取临时推广二维码的事件。
     * 
     * @param openId     用户的openId
     * @param officialId 公众号的openId
     * @return 返回微信回复的消息，包含生成的临时二维码图片。
     * @throws IOException 如果文件处理过程中发生错误。
     */
    public String handleClickForGetTemporaryQRCodeForPromotion(String openId, String officialId) throws IOException {
        // 创建一个有效期为30天的临时参数二维码
        String qrLink = WeChatService.createTemporaryParametricQRCode(openId, 2592000);
        String destination = openId + ".jpg";
        // 下载二维码图片
        Filemanege.downloadImg(qrLink, destination);
        // 将下载的图片添加到微信临时素材库
        JSONObject material = WeChatService.addTemporaryMaterial(destination, "image");
        // 删除本地已下载的文件
        Filemanege.deleteFile(destination);
        // 从返回的素材信息中获取media_id
        String mediaId = material.getString("media_id");
        // 解析二维码链接中的ticket参数
        String ticket = StringUtils.getUrlParam(qrLink, "ticket");
        // 创建推广二维码对象并保存到数据库
        QrCodeForPromotion qrCodeForPromotion = new QrCodeForPromotion(mediaId, openId, "t", ticket,
                new Date());
        qrCodeRepository.save(qrCodeForPromotion);
        // 构建并返回包含临时二维码图片的微信回复消息
        return WeChatService.buildImageReply(openId, officialId, mediaId);
    }

    public String handleClickForPromotionData(String openId, String officailId) {
        List<User> followings = userRepository.findAllByIntroducerAndFollowing(openId, true);
        List<User> noFollowing = userRepository.findAllByIntroducerAndFollowing(openId, false);
        String content = String.format("您的推广战绩：\n正在关注的用户数：%d\n取消关注的用户数：%d", followings.size(), noFollowing.size());
        return WeChatService.buildTextReply(openId, officailId, content);
    }
}
